/*
 * (x) Henrique Jotha 2011
 * 
 * Popula o banco de dados a partir dos arquivos:
 * 
 * usuarios.txt
 * 
 */
package br.unirio.bsi.mono.ForumLoader;

import java.io.FileNotFoundException;

import br.unirio.bsi.mono.ForumSite.model.Usuario;
import br.unirio.bsi.mono.ForumSite.model.Comentario;

import br.unirio.bsi.mono.ForumSite.model.dao.GenericDAO;

// holder instances impl
class UsuarioImpl extends Usuario {}
class ComentarioImpl extends Comentario {}

public class Loader 
{
  public static final String DB_NAME = "FORUM";

  private static final String DB_BIN_PATH = "C:\\Program Files\\PostgreSQL\\9.0\\bin\\";  
  
  private static final String DB_DROP_CMD = "dropdb -h localhost -U postgres " + DB_NAME;
  private static final String DB_CREATE_CMD = "createdb -h localhost -U postgres " + DB_NAME;
  
  private static final String DATA_PATH = "..\\..\\spec\\BaseDados\\";
  
  // OPERATION FLAGS -- CHANGE ACCORDINGLY
  private static final boolean DROP_DB = false;
  private static final boolean LOAD_DB = false;
  
  public static void main(String[] args) 
  {     
    try
    {       
      if( DROP_DB ) 
      {
        // delete the database 
        Process pddb = Runtime.getRuntime().exec(DB_BIN_PATH + DB_DROP_CMD);
        pddb.waitFor();

        // create the database
        Process pcdb = Runtime.getRuntime().exec(DB_BIN_PATH + DB_CREATE_CMD);
        pcdb.waitFor();
      }

      // pega instancia do DAO
      GenericDAO gD = GenericDAO.getInstance( DB_NAME );

      if( LOAD_DB )
      {
        // carrega o script do banco
        gD.executeFile( DATA_PATH + DB_NAME + ".sql" );      
      }
      
      // READERS
      // carrega a lista inicial de comentarios
      Reader rc = new Reader<ComentarioImpl>( DATA_PATH, '#', ComentarioImpl.class );      
      // carrega a lista inicial de usuarios
      Reader ru = new Reader<UsuarioImpl>( DATA_PATH, '#', UsuarioImpl.class );

      // insere cada Comentario
      System.out.println("Inserindo Comentarios...");      
      for( Comentario c : (Comentario[])rc.getGenericsList() )
        gD.insert( c );

      // insere cada Usuario
      System.out.println("Inserindo Usuarios...");      
      for( Usuario u : (Usuario[])ru.getGenericsList() )
        gD.insert( u );
      
      // nothingness  
      gD = null;
      ru = null;
    }
    catch( FileNotFoundException ex )
    {
      System.out.println("Cannot find file:" + ex.toString() );
    }
    catch( Exception e )
    {
      System.out.println("Erro: " + e.getMessage());
    }
  }
}
